
#include "list_node_add.h"

ListNode *Solution1::addTwoNumbersByStep(int step, ListNode *l1, ListNode *l2)
{
    ListNode *currentNode=nullptr;
    ListNode *head=nullptr;
    do
    {
        ListNode *newNode = (ListNode *)nullptr;
        if (l1 == nullptr && l2 == nullptr && step == 0)
        {
            newNode = (ListNode *)nullptr;
        }
        else
        {

            if (l1 == nullptr && l2 == nullptr && step != 0)
            {
                newNode = new ListNode();
                newNode->val = step;
                step = 0;
                l1 = nullptr;
                l2 = nullptr;
            }
            else
            {
                newNode = new ListNode();

                newNode->val = (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val) + step;
                int nextStep = 0;
                if (newNode->val >= 10)
                {
                    newNode->val = newNode->val - 10;
                    nextStep = 1;
                }

                step = nextStep;
                l1 = (l1 == nullptr ? nullptr : l1->next);
                l2 = (l2 == nullptr ? nullptr : l2->next);
            }
        }
        if (currentNode != nullptr)
        {
            currentNode->next = newNode;
            currentNode = currentNode->next;
        }
        else
        {
            currentNode = newNode;
            if (head == nullptr)
            {
                head = currentNode;
            }
        }
    } while (currentNode != nullptr);
    return head;
}

ListNode * Solution1::addTwoNumbers(ListNode *l1, ListNode *l2)
{
    if (l1->val >= 10 || l1->val < 0)
    {
        return nullptr;
    }
    if (l2->val >= 10 || l2->val < 0)
    {
        return nullptr;
    }

    return addTwoNumbersByStep(0, l1, l2);
}
